import java.security.SecureRandom;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

/**
 * 实现一个多线程，并行处理，等待所有的线程结束之后，所有线程的处理时间参差不齐，有5s，有10s，有1s，
 * 但是需要确保所有的线程处理结束之后，主线程才能结束并且需要立刻结束。
 */
public class CountDownLatchMain {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);

        IntStream.range(0, 10).forEach(index -> {
            new Thread(() -> {
                long start = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + " start");
                try {
                    Thread.sleep(new SecureRandom().nextInt(10) * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                long end = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + " done, duration: " + (end - start));

                latch.countDown();
            }).start();

        });

        latch.await();

        System.out.println(Thread.currentThread().getName() + " done");
    }
}
